<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开权限框区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i === 0 ? 'bdtop' : '', 'vcenter']"
              :key="item.id"
              v-for="(item, i) in scope.row.children"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="delRightById(scope.row, item.id)" closable>
                  {{ item.authName }} </el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级&三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i1 === 0 ? '' : 'bdtop', 'vcenter']"
                  :key="item1.id"
                  v-for="(item1, i1) in item.children"
                >
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      @close="delRightById(scope.row, item1.id)"
                      closable
                    >
                      {{ item1.authName }} </el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-col
                      ><el-tag
                        @close="delRightById(scope.row, item2.id)"
                        closable
                        type="warning"
                        :key="item2.id"
                        v-for="item2 in item1.children"
                      >
                        {{ item2.authName }}
                      </el-tag></el-col
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              @click="showSetDialogVisible(scope.row)"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="60%">
      <el-form
        :model="addForm"
        ref="ruleFormRef"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="60%">
      <el-form
        :model="editForm"
        ref="ruleFormRef"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole(editForm.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="80%">
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 添加角色model
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          {
            min: 0,
            max: 10,
            message: '长度在 0 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      // 树形权限列表
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 角色列表
      rolesList: [],
      // 对话框
      addDialogVisible: false,
      editDialogVisible: false,
      setDialogVisible: false,
      // 角色ID
      editForm: {},
      // 权限数据
      rightslist: [],
      // 默认选中权限id
      defKeys: [],
      // 新添加的角色权限ID
      roleId: ''
    }
  },
  // 页面加载获取角色列表
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 添加角色
    addRole () {
      // 预验证
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.addDialogVisible = false
        this.getRolesList()
      })
    },
    // 获取角色ID
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      this.editForm = res.data
      // console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 编辑角色
    editRole (id) {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + id, this.editForm)
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    async delRole (id) {
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    },
    // 删除角色权限
    async delRightById (role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('取消权限失败')
      }
      this.$message.success('取消权限成功')
      // 避免页面刷新权限菜单关闭
      role.children = res.data
    },
    // 获取权限列表
    async showSetDialogVisible (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败!')
      }
      this.rightslist = res.data
      this.defKeys = []
      this.getLeafKeys(role, this.defKeys)
      this.setDialogVisible = true
    },
    // 用递归获取权限id
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 分配用户权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色权限失败')
      }
      this.$message.success('分配角色权限成功')
      this.getRolesList()
      this.setDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  margin-bottom: 0;
}
</style>
